//
//  FindWordViewController.m
//  ZiJinLian
//
//  Created by 🐛 on 2017/4/11.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "FindWordViewController.h"
#import "SetPayWordViewController.h"
#import "NewRegistViewController.h"
@interface FindWordViewController ()<UITextFieldDelegate>

@property(nonatomic ,strong) UITextField *phoneWord;
@property(nonatomic ,strong) UITextField *passWord1;
@property(nonatomic ,strong) UITextField *file;
@property(nonatomic ,strong) UIButton *GetNumeberBtn;
@property(nonatomic ,strong) NSDictionary *dicSms;

@end

@implementation FindWordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.type==2) {
         self.title=MyString(@"修改登录密码");
    }else if(self.type==3||self.type==1){
        //银行卡
         self.title=MyString(@"验证手机");
    }else{
        //微信登录绑定手机号
        self.title=MyString(@"绑定手机");
    }
   
    // Do any additional setup after loading the view.
}
//找回密码
-(void)createView{
    self.phoneWord=[[UITextField alloc]initWithFrame:CGRectMake(10, 30, MainW-20, 49)];
    self.phoneWord.font=FontAndStyle14;
    self.phoneWord.textColor=TextColor3;
    self.phoneWord.placeholder=MyString(@"请输入手机号");
    [self.phoneWord setValue:FontAndStyle14 forKeyPath:@"_placeholderLabel.font"];
    self.phoneWord.keyboardType=UIKeyboardTypeNumberPad;
    self.phoneWord.delegate=self;
    self.phoneWord.backgroundColor=[UIColor whiteColor];
    [self.phoneWord addTarget:self action:@selector(controlTextDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.phoneWord.borderStyle=UITextBorderStyleNone;
    [self.view addSubview:self.phoneWord];
    UILabel *paddingView = [[UILabel alloc] init];
    //1 是验证手机号  2是修改登录密码
    if (self.type==2) {
        paddingView.text = @"验证手机号";
    }else{
        paddingView.text = @"手机号";
    }
    
    paddingView.font=FontAndStyle14;
    paddingView.textColor = TextColor6;
    paddingView.backgroundColor = [UIColor clearColor];
    CGSize size=[paddingView.text sizeWithAttributes:@{NSFontAttributeName:paddingView.font }];
    paddingView.frame=CGRectMake(5, 15, size.width+15, 20);
    UIView*view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, size.width+15, 50)];
    view.backgroundColor=[UIColor clearColor];
    [view addSubview:paddingView];
    self.phoneWord.leftView = view;
    self.phoneWord.leftViewMode = UITextFieldViewModeAlways;
    
    
    
    
    CGFloat weith=(MainW-25)*9/25;
    self.passWord1=[[UITextField alloc]initWithFrame:CGRectMake(10, 110, MainW-weith-25, 49)];
    self.passWord1.delegate=self;
    self.passWord1.font=FontAndStyle14;
    self.passWord1.textColor=TextColor3;
    self.passWord1.backgroundColor=[UIColor whiteColor];
    self.passWord1.placeholder=MyString(@"  请输入验证码");
    [self.passWord1 setValue:FontAndStyle14 forKeyPath:@"_placeholderLabel.font"];
    self.passWord1.keyboardType=UIKeyboardTypeNumberPad;
    self.passWord1.borderStyle=UITextBorderStyleNone;
    [self.view addSubview:self.passWord1];
    [self.passWord1 addTarget:self action:@selector(controlTextDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.file=[[UITextField alloc]initWithFrame:CGRectMake(MainW-weith-10, 110, weith, 49)];
    self.file.placeholder=MyString(@"获取验证码");
    self.file.enabled=NO;
    self.file.backgroundColor=[UIColor whiteColor];
    [self.file setValue:Red_Color forKeyPath:@"_placeholderLabel.textColor"];
    [self.file setValue:FontAndStyle14 forKeyPath:@"_placeholderLabel.font"];
    self.file.keyboardType=UIKeyboardTypeNumberPad;
    self.file.borderStyle=UITextBorderStyleNone;
    [self.view addSubview:self.file];
    UILabel * placeholderLabel = [self.file valueForKey:@"_placeholderLabel"];
    placeholderLabel.textAlignment = NSTextAlignmentCenter;
    
    self.GetNumeberBtn=[[UIButton alloc]initWithFrame:CGRectMake(MainW-weith-10, 110, weith, 49)];
    [self.GetNumeberBtn addTarget:self action:@selector(GetNumeberBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.GetNumeberBtn.backgroundColor=[UIColor clearColor];
    [self.view addSubview:self.GetNumeberBtn];
    
    UIButton *NextBtn=[[UIButton alloc]initWithFrame:CGRectMake(10, 180, MainW-20, 50)];
    [NextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [NextBtn setTitle:MyString(@"确定") forState:UIControlStateNormal];
    [NextBtn addTarget:self action:@selector(NextBtn) forControlEvents:UIControlEventTouchUpInside];
    [NextBtn setBackgroundColor:Red_Color];
    [self.view addSubview:NextBtn];
    ViewRadius(NextBtn, 5);
    ViewRadius(self.passWord1, 3);
    ViewRadius(self.phoneWord, 3);
    ViewRadius(self.file, 3);
}
-(void)NextBtn{
    if (self.phoneWord.text.length!=0) {
        if (![ZJUITools checkTel:self.phoneWord.text]) {
            [self showToast:MyString(@"请输入正确的手机号码")];
        }else{
            if (self.passWord1.text.length==0) {
                [self showToast:MyString(@"请输入验证码")];
            }else{
                NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
                dic[@"phone"]=self.phoneWord.text;
                dic[@"smsCode"]=self.passWord1.text;
                [self doHttpRequestWithApi:API_CHECK_SMS method:GET dic:dic successBlock:^(NSDictionary *dic) {
                    if ([dic[@"status"] intValue]==0) {
                        //NSLog(@"绑定 :%@",dic[@"msg"]);
                        if (self.type==4) {
                            if ([self.dicSms[@"data"] intValue]==1) {
                                if (self.logintype==1) {
                                    [self QQLoginClick];
                                }else{
                                    [self wechatLoginClick];
                                }
                                
                            }else{
                                NewRegistViewController *vc=[[NewRegistViewController alloc]init];
                                vc.type=self.logintype;
                                vc.phone=self.phoneWord.text;
                                vc.smsCode=self.passWord1.text;
                                [self.navigationController pushViewController:vc animated:YES];
                            }
                            
                            return ;
                        }else if (self.type==3){
                            [self bindBankRequest];
                            //NSLog(@"银行卡");
                        }else{
                            SetPayWordViewController *vc=[[SetPayWordViewController alloc]init];
                            if (self.type==2) {
                                vc.statue=2;
                                vc.type=2;
                            }else{
                                vc.statue=3;
                            }
                            [self.navigationController pushViewController:vc animated:YES];
                        }
                        

                    }else{
                        
                        [self showToast:dic[@"msg"]];
                    }
                    
                }];
            }
        }
        //[self startTime];
    }else{
        [self showToast:MyString(@"请输入手机号码")];
    }
}
-(void)GetNumeberBtnClick{
    if (self.phoneWord.text.length!=0) {
        if (![ZJUITools checkTel:self.phoneWord.text]) {
            [self showToast:MyString(@"请输入正确的手机号码")];
            return;
        }
        NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
        
        [parametersDic setObject:self.phoneWord.text forKey:@"phone"];
        if (self.type==4) {
            [parametersDic setObject:@"1" forKey:@"checkPhone"];
        }else{
            [parametersDic setObject:@"0" forKey:@"checkPhone"];
        }
        
        
        [self doHttpRequestWithApi:API_SEND_SMS method:POST dic:parametersDic successBlock:^(NSDictionary *dic) {
            [self showMessage:MyString(@"验证码发送成功，请查收") ];
            self.dicSms=dic;
        }];
        [self startTime];
    }else{
        [self showToast:MyString(@"手机号码不能为空")];
    }
    
}
- (void)startTime
{
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0)
        { //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                self.file.placeholder=MyString(@"获取验证码");
                self.phoneWord.enabled=YES;
                self.GetNumeberBtn.userInteractionEnabled = YES;
            });
        }
        else
        {
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //self.phoneWord.enabled=NO;
                self.file.placeholder=[NSString stringWithFormat:@"%@%@",strTime,MyString(@"秒后重试")];
                self.GetNumeberBtn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
-(void)controlTextDidChange:(NSNotification *)obj {
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self performSelector:@selector(nizana) withObject:obj afterDelay:3.0];
}
-(void)nizana{
    //NSLog(@"监听到了吗");
    [self.phoneWord resignFirstResponder];
    [self.passWord1 resignFirstResponder];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self.phoneWord resignFirstResponder];
    [self.passWord1 resignFirstResponder];
}
-(void)wechatLoginClick{
    NSMutableDictionary*dic=[NSMutableDictionary dictionary];
    dic[@"smsCode"]=self.passWord1.text;
    dic[@"phone"]=self.phoneWord.text;
    dic[@"code"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"WXCode"];
    [self doHttpRequestWithApi:API_WechatLOGINbinding method:POST dic:dic successBlock:^(NSDictionary *dic) {
        if ([dic[@"status"] intValue]==143) {
            [self showToast:MyString(@"该手机号已被绑定")];
        }else if ([dic[@"status"] intValue]==142){
            
        }else if ([dic[@"status"] intValue]==141){
            
        }else{
            [ZJUserDefaultsTools saveUserInfoLocal:dic];
            [[EMClient sharedClient] loginWithUsername:[ZJUserDefaultsTools getCurrentIMName]
                                              password:[ZJUserDefaultsTools getCurrentIMPASSWORD]
                                            completion:^(NSString *aUsername, EMError *aError) {
                                                if (!aError) {
                                                    //NSLog(@"登录成功");
                                                    EMPushOptions *emoptions = [[EMClient sharedClient] pushOptions];
                                                    //设置有消息过来时的显示方式:1.显示收到一条消息 2.显示具体消息内
                                                    [[EMClient sharedClient].options setIsAutoLogin:YES];
                                                    //自己可以测试下
                                                    emoptions.displayStyle = EMPushDisplayStyleSimpleBanner;
                                                    [[EMClient sharedClient] updatePushOptionsToServer];
                                                } else {
                                                    //NSLog(@"登录失败");
                                                }
                                            }];
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        
        
    }];

}
-(void)QQLoginClick{
    NSMutableDictionary*dic=[NSMutableDictionary dictionary];
    dic[@"smsCode"]=self.passWord1.text;
    dic[@"phone"]=self.phoneWord.text;
    dic[@"openKey"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"QQopenKey"];
    dic[@"openId"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"QQopenid"];;
    dic[@"pf"]=@"openmobile_ios";
    [self doHttpRequestWithApi:API_QQLOGINbinding method:GET dic:dic successBlock:^(NSDictionary *dic) {
        if ([dic[@"status"] intValue]==143) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UIViewController *viewCtl = self.navigationController.viewControllers[0];
                [self.navigationController popToViewController:viewCtl animated:YES];
            });
        }else if ([dic[@"status"] intValue]==142){
            [ZJUserDefaultsTools saveUserInfoLocal:dic];
            [self dismissViewControllerAnimated:YES completion:nil];
        }else if ([dic[@"status"] intValue]==141){
            
        }else{
            [ZJUserDefaultsTools saveUserInfoLocal:dic];
            [[EMClient sharedClient] loginWithUsername:[ZJUserDefaultsTools getCurrentIMName]
                                              password:[ZJUserDefaultsTools getCurrentIMPASSWORD]
                                            completion:^(NSString *aUsername, EMError *aError) {
                                                if (!aError) {
                                                    //NSLog(@"登录成功");
                                                    EMPushOptions *emoptions = [[EMClient sharedClient] pushOptions];
                                                    //设置有消息过来时的显示方式:1.显示收到一条消息 2.显示具体消息内
                                                    [[EMClient sharedClient].options setIsAutoLogin:YES];
                                                    //自己可以测试下
                                                    emoptions.displayStyle = EMPushDisplayStyleSimpleBanner;
                                                    [[EMClient sharedClient] updatePushOptionsToServer];
                                                } else {
                                                    //NSLog(@"登录失败");
                                                }
                                            }];
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        
        
    }];
    
}
-(void)bindBankRequest{
    NSMutableDictionary*dic=[NSMutableDictionary dictionary];
    dic[@"creditName"]=[NSString stringWithFormat:@"%@",[self.dic objectForKey:@"creditName"]];
    dic[@"creditAccount"]=[NSString stringWithFormat:@"%@",[self.dic objectForKey:@"creditBank"]];
    dic[@"creditBank"]=[NSString stringWithFormat:@"%@",[self.dic objectForKey:@"creditAccount"]];
    dic[@"smsCode"]=self.passWord1.text;
    dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
    //NSLog(@"------%@",dic);
    [self doHttpRequestWithApi:BINDBANKCARD method:GET dic:dic successBlock:^(NSDictionary *dic) {
        //NSLog(@"绑定成功啊");
        UIViewController *viewCtl = self.navigationController.viewControllers[2];
        [self.navigationController popToViewController:viewCtl animated:YES];
    }];
}
@end
